package com.chookss.home.logContacts;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.base.StaticClass;
import com.chookss.home.entity.ContactEntity;
import com.chookss.home.interview.InterviewDetailActivity;
import com.chookss.mine.personal.PersonalHomeActivity;
import com.chookss.tiku.view.FlowLayout;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.NavigationTools;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.CircleImageView;
import com.google.gson.reflect.TypeToken;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.lvgroup.hospital.base.BaseAct;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;
import scut.carson_ho.searchview.EditText_Clear;

//日志选择人员
public class ContactsLogChoiceActivity extends BaseAct {
    @BindView(R.id.et_search)
    EditText_Clear etSearch;
    @BindView(R.id.common_title_txt)
    TextView common_title_txt;
    @BindView(R.id.tvCompany)
    TextView tvCompany;
    @BindView(R.id.rvView)
    RecyclerView rvView;
    @BindView(R.id.srlView)
    SmartRefreshLayout srlView;
    @BindView(R.id.llSearchEmpty)
    LinearLayout llSearchEmpty;
    @BindView(R.id.ivSearchEmpty)
    ImageView ivSearchEmpty;
    @BindView(R.id.tvSearchEmpty)
    TextView tvSearchEmpty;
    @BindView(R.id.tv2SearchEmpty)
    TextView tv2SearchEmpty;
    @BindView(R.id.tvBottomNum)
    TextView tvBottomNum;
    @BindView(R.id.ivBottomSure)
    TextView ivBottomSure;
    @BindView(R.id.rlBottom)
    RelativeLayout rlBottom;
    @BindView(R.id.rlSearch)
    RelativeLayout rlSearch;
    @BindView(R.id.ivAllStatus)
    ImageView ivAllStatus;
    @BindView(R.id.rlAllSelect)
    RelativeLayout rlAllSelect;
    @BindView(R.id.ivBottomInit)
    TextView ivBottomInit;
    @BindView(R.id.tvChoiceInit)
    TextView tvChoiceInit;
    @BindView(R.id.flowLayout)
    FlowLayout flowLayout;
    private String key = "", companyNmae = "", oldCompanyNmae = "";//关键字、组织名、部门
    private ContactsAdapter adapter;
    private List<ContactEntity> list = new ArrayList<>();

    private int currentPage = 1;
    private boolean isEnd = false;//是否到底
    private boolean allSelect = false;//是否全选
    private int selectAllNum = 0;//整个组织选中的总人数
    private int pepleNum = 0;//当前页面选中的总人数
    private int allNum = 0;//当前页面总人数
    private ArrayList<String> nameList = new ArrayList<>();//组织及部门排列
    private FlowAdapter nameAdapter;
    private String lpFlag = "";//0禁止1正常
    private boolean oldDepartmentStatus = false;//上一层级归属部门是否全选
    private String orgCode = "";//上一层级归属部门code
    private String hierarchyOrgCode = "";//之前各个层级以_链接
    private ContactEntity oldDepartmentEntity = null;//上一层级归属部门实体类
    private String source = "4";//1暂时废弃2面试3分组过来选择人的4日志筛选5工作台选人6学习任务选人7图库(只能选择一个，需要单选）8图库多选筛选9物品交接单选的10计步器活动多选
    private int oldContactNum = 0;//来源3的时候本有的人员数量
    private String hrName = "", examCode = "", examName = "", qrCodeValid = "";//只有来源2的情况下才存在
    private int singleIndex = -1;//单选人员下标  只有来源7的情况下才存在

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contacts_choice);
        ButterKnife.bind(this);
        source = getIntent().getStringExtra("source");
        oldContactNum = getIntent().getIntExtra("oldContactNum", 0);
        lpFlag = new ShareUtils().getString(this, StaticClass.LP_FLAG, "1");
        //禁止截屏
        if ("0".equals(lpFlag)) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
        }
        hrName = getIntent().getStringExtra("hrName");
        examCode = getIntent().getStringExtra("examCode");
        examName = getIntent().getStringExtra("examName");
        qrCodeValid = getIntent().getStringExtra("qrCodeValid");
        if (Utils.isNull(hrName)) {
            hrName = "已选择：";
            KLog.i(hrName + "=======");
        } else {
            KLog.i(hrName + "--");
        }
        tvChoiceInit.setText("全选");
        oldDepartmentStatus = getIntent().getBooleanExtra("oldDepartmentStatus", false);
        orgCode = getIntent().getStringExtra("orgCode");
        key = getIntent().getStringExtra("key");
        companyNmae = getIntent().getStringExtra("companyNmae");
        oldDepartmentEntity = (ContactEntity) getIntent().getSerializableExtra("oldDepartmentEntity");
        hierarchyOrgCode = getIntent().getStringExtra("hierarchyOrgCode");
        oldCompanyNmae = getIntent().getStringExtra("oldCompanyNmae");
        ArrayList<String> nameLists = getIntent().getStringArrayListExtra("nameList");
        if (nameLists != null) {
            nameList.addAll(nameLists);
            nameList.add(oldCompanyNmae);
        }
        if ("2".equals(source)) {
            rlAllSelect.setVisibility(View.GONE);
            common_title_txt.setText("选择面试官");
            ivBottomSure.setText("不选了");
        } else if ("3".equals(source)) {
            common_title_txt.setText("选择分组成员");
            ivBottomSure.setText("不选了");
        } else if ("7".equals(source)) {
            //图库发布不能全选  只能单选
            rlAllSelect.setVisibility(View.GONE);
            common_title_txt.setText("选择提供者");
        } else if ("8".equals(source)) {
            //图库多选
            common_title_txt.setText("选择提供人");
        } else if ("9".equals(source)) {
            //物品交接发布不能全选  只能单选
            rlAllSelect.setVisibility(View.GONE);
            common_title_txt.setText("选择员工");
        } else if ("10".equals(source)) {
            //计步器功能
            common_title_txt.setText("选择成员");
        } else if ("11".equals(source)) {
            //项目组选人
            common_title_txt.setText("选择项目组成员");
            ivBottomSure.setText("不选了");
        } else {
            common_title_txt.setText("选择员工");
        }
        NavigationTools.setWaterMark(this, "15");
    }

    @Override
    public void initData() {
        initState();
        rlSearch.setVisibility(View.VISIBLE);
        ivBottomInit.setText(hrName);
        if (nameList.size() > 0) {
            flowLayout.setVisibility(View.VISIBLE);
            tvCompany.setVisibility(View.GONE);
            nameAdapter = new FlowAdapter(this, nameList);
            flowLayout.setAdapter(nameAdapter);
        } else {
            companyNmae = new ShareUtils().getString(this, StaticClass.COMPANYNAME, "");
            if (Utils.isNull(companyNmae)) {
                companyNmae = getResources().getString(R.string.app_name);
            }
            nameList.add(companyNmae);
            flowLayout.setVisibility(View.GONE);
            tvCompany.setVisibility(View.VISIBLE);
            tvCompany.setText(companyNmae);
        }
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {   // 按下完成按钮，这里和上面imeOptions对应
                    if (!Utils.isNull(v.getText().toString())) {
                        key = v.getText().toString();
                        etSearch.setText(key);
                        tvCompany.setText(companyNmae);
                        tvCompany.setVisibility(View.VISIBLE);
                        flowLayout.setVisibility(View.GONE);
                        isEnd = false;
                        currentPage = 1;
                        showLoading();
                        getData();
                        allSelect = false;
                        ivAllStatus.setBackgroundResource(R.drawable.shape_circle_dddddd_10);
                        return false;   //返回true，保留软键盘。false，隐藏软键盘
                    } else {
                        MyToast.show("请输入关键词");
                    }
                }
                return true;   //返回true，保留软键盘。false，隐藏软键盘
            }
        });
        rvView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        adapter = new ContactsAdapter(R.layout.item_contacts_choice, list);
        rvView.setAdapter(adapter);
        srlView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (Utils.isNull(key)) {
                    //不能分页
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    //搜索可以分页
                    if (isEnd) {//has next page
                        MyToast.show("没有更多数据了");
                        loadEnd();
                    } else {
                        currentPage++;
                        getData();
                    }
                }
            }
        });
        srlView.setEnableRefresh(false);
        showLoading();
        getData();
    }

    private void getData() {
        Map<String, String> map = new HashMap<>();
        String url = "";
        if (Utils.isNull(key)) {
            map.put("orgCode", orgCode);
            url = Urls.selectOrgAndEmpByCodeNoPage;
        } else {
            map.put("searchParam", key);
            url = Urls.selectEmpByParam;
        }
        map.put("pageNum", currentPage + "");
        map.put("pageSize", "50");
        map.put("type", "1");
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<ContactEntity>>>() {
                }.getType(), null, url, SignUtils2.makeSignStr(map), false,
                new ObserverCallback<List<ContactEntity>>() {
                    @Override
                    public void onSuccess(List<ContactEntity> data) {
                        dismissLoading();
                        loadEnd();
                        if (currentPage == 1 || Utils.isNull(key)) {
                            list.clear();
                            allNum = 0;
                        }
                        if (llSearchEmpty == null || rvView == null) {
                            return;
                        }
                        if (data.size() == 0) {
                            isEnd = true;
                            if (list.size() == 0) {
                                rvView.setVisibility(View.GONE);
                                llSearchEmpty.setVisibility(View.VISIBLE);
                                //筛选组织的时候，没有数据，表示么有权限
                                flowLayout.setVisibility(View.GONE);
                                if (Utils.isNull(key)) {
                                    tvSearchEmpty.setText("暂无可选人员");
                                    tv2SearchEmpty.setVisibility(View.GONE);
                                }

                            }
                        } else {
                            if ("3".equals(source) || "11".equals(source)) {
                                //只能新增已经存在的要去除
                                for (int i = 0; i < data.size(); i++) {
                                    list.add(data.get(i));
                                    for (int j = 0; j < MyApp.contactEntityLogList.size(); j++) {
                                        if (MyApp.contactEntityLogList.get(j).getEmployeeCode().equals(data.get(i).getEmployeeCode())) {
                                            list.remove(list.size() - 1);
                                        }
                                    }
                                }
                            } else {
                                //剩余情况
                                list.addAll(data);
                            }
                            if (list.size() == 0) {
                                rvView.setVisibility(View.GONE);
                                llSearchEmpty.setVisibility(View.VISIBLE);
                                //筛选组织的时候，没有数据，表示么有权限
                                flowLayout.setVisibility(View.GONE);
                                if (Utils.isNull(key)) {
                                    tvSearchEmpty.setText("暂无可选人员");
                                    tv2SearchEmpty.setVisibility(View.GONE);
                                }
                            } else {
                                rvView.setVisibility(View.VISIBLE);
                                llSearchEmpty.setVisibility(View.GONE);
                                initOldData();
                                adapter.notifyDataSetChanged();
                            }
                        }

                    }

                    @Override
                    public void onError(String errorMsg) {
                        dismissLoading();
                        loadEnd();
                        MyToast.show(Utils.onErrorTips(errorMsg));
                    }
                });
    }

    private void initOldData() {
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getType().equals("1")) {
                allNum = allNum + 1;
            } else {
                allNum = allNum + Utils.changeNumber(list.get(i).getEmpNum());
            }
            if (!Utils.isNull(hierarchyOrgCode)) {
                list.get(i).setHierarchyOrgCode(hierarchyOrgCode);
            }
            if (oldDepartmentStatus) {
                //上一层级选择了
                list.get(i).setSelect(true);
                list.get(i).setHalfSelect(false);
                for (int j = 0; j < MyApp.contactEntityLogList.size(); j++) {
                    if (list.get(i).getEmployeeCode().equals(MyApp.contactEntityLogList.get(j).getEmployeeCode())) {
                        MyApp.contactEntityLogList.remove(j);
                        if (j < MyApp.contactEntityLogList.size()) {
                            j--;
                        }
                    } else if (MyApp.contactEntityLogList.get(j).getHierarchyOrgCode().contains(list.get(i).getEmployeeCode())) {
                        MyApp.contactEntityLogList.remove(j);
                        if (j < MyApp.contactEntityLogList.size()) {
                            j--;
                        }
                    }
                }
                MyApp.contactEntityLogList.add(list.get(i));
                if (i == list.size() - 1) {
                    setAllNum(false);
                }
            } else {
                for (int j = 0; j < MyApp.contactEntityLogList.size(); j++) {
                    if (list.get(i).getEmployeeCode().equals(MyApp.contactEntityLogList.get(j).getEmployeeCode())) {
                        if (MyApp.contactEntityLogList.get(j).isHalfSelect()) {
                            list.get(i).setSelect(false);
                            list.get(i).setHalfSelect(true);
                        } else {
                            list.get(i).setSelect(true);
                            list.get(i).setHalfSelect(false);
                        }
                    }
                    if (i == list.size() - 1 && j == MyApp.contactEntityLogList.size() - 1) {
                        setAllNum(false);
                    }
                }
            }

        }
        if (MyApp.contactEntityLogList.size() == 0) {
            ivBottomSure.setText("不选了");
        }

    }

    class ContactsAdapter extends BaseQuickAdapter<ContactEntity, BaseViewHolderEx> {

        public ContactsAdapter(int layoutResId, List<ContactEntity> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolderEx helper, ContactEntity entity) {
            //组织
            LinearLayout llCompany = helper.getView(R.id.llCompany);
            ImageView ivStatus = helper.getView(R.id.ivStatus);
            RelativeLayout rlStatus = helper.getView(R.id.rlStatus);
            RelativeLayout halfRl = helper.getView(R.id.halfRl);//部门下有人被选中，但不是所有人被选中的状态 半选
            TextView tvContactsName = helper.getView(R.id.tvContactsName);
            TextView tvContactsNum = helper.getView(R.id.tvContactsNum);
            View spaceView = helper.getView(R.id.spaceView);
            //员工
            LinearLayout llEmployees = helper.getView(R.id.llEmployees);
            ImageView ivEmployeesStatus = helper.getView(R.id.ivEmployeesStatus);
            CircleImageView ivEmployees = helper.getView(R.id.ivEmployees);
            RelativeLayout rlEmployeesStatus = helper.getView(R.id.rlEmployeesStatus);
            TextView tvEmployeesName = helper.getView(R.id.tvEmployeesName);
            TextView tvEmployeesJob = helper.getView(R.id.tvEmployeesJob);
            View employeesSpaceView = helper.getView(R.id.employeesSpaceView);
            if ("0".equals(entity.getType())) {
                //部门
                llCompany.setVisibility(View.VISIBLE);
                llEmployees.setVisibility(View.GONE);
                if (Utils.changeNumber(entity.getEmpNum()) == 0) {
                    //灰色不可选中
                    tvContactsName.setTextColor(Color.parseColor("#999999"));
                    tvContactsNum.setTextColor(Color.parseColor("#999999"));
                    ivStatus.setBackgroundResource(R.drawable.shape_circle_dddddd_10);
                    halfRl.setVisibility(View.GONE);
                    ivStatus.setVisibility(View.VISIBLE);
                } else {
                    tvContactsName.setTextColor(Color.parseColor("#333333"));
                    tvContactsNum.setTextColor(Color.parseColor("#333333"));
                    if (allSelect) {
                        ivStatus.setBackgroundResource(R.drawable.icon_fx_select);
                        halfRl.setVisibility(View.GONE);
                        ivStatus.setVisibility(View.VISIBLE);
                    } else {
                        if (entity.isSelect()) {
                            ivStatus.setBackgroundResource(R.drawable.icon_fx_select);
                            halfRl.setVisibility(View.GONE);
                            ivStatus.setVisibility(View.VISIBLE);
                        } else {
                            if (entity.isHalfSelect()) {
                                halfRl.setVisibility(View.VISIBLE);
                                ivStatus.setVisibility(View.GONE);
                            } else {
                                ivStatus.setBackgroundResource(R.drawable.shape_circle_bbbbbb_10);
                                halfRl.setVisibility(View.GONE);
                                ivStatus.setVisibility(View.VISIBLE);
                            }

                        }
                    }
                }
                if ("2".equals(source) || "7".equals(source) || "9".equals(source)) {
                    //面试不得选部门  图库提供者不得选部门   物品交接者不得选部门
                    spaceView.setVisibility(View.VISIBLE);
                    rlStatus.setVisibility(View.GONE);
                } else {
                    spaceView.setVisibility(View.GONE);
                    rlStatus.setVisibility(View.VISIBLE);
                }
                tvContactsName.setText(entity.getEmployeeName());
                tvContactsNum.setText("(" + entity.getEmpNum() + ")");
            } else {
                //员工
                llCompany.setVisibility(View.GONE);
                llEmployees.setVisibility(View.VISIBLE);
                GlideUtils.loadAvatar(ContactsLogChoiceActivity.this,
                        entity.getHeadPhotoThumbUrl(), ivEmployees);

                if (Utils.isNull(key)) {
                    tvEmployeesName.setText(entity.getEmployeeName());
                } else {
                    tvEmployeesName.setText(Utils.matcherSearchTitle(getResources().getColor(R.color.main_color), entity.getEmployeeName(), key));
                }
                tvEmployeesJob.setText(entity.getPost());
                //和日志结合,暂时未做
                employeesSpaceView.setVisibility(View.GONE);
                rlEmployeesStatus.setVisibility(View.VISIBLE);
                if (("2".equals(source) || "3".equals(source) || "11".equals(source) || "9".equals(source) || "10".equals(source)) && entity.getEmployeeCode().equals(new ShareUtils().getString(ContactsLogChoiceActivity.this, StaticClass.EMPLOYEECODE, ""))) {
                    //不能选择本人
                    rlEmployeesStatus.setVisibility(View.INVISIBLE);
                } else {
                    rlEmployeesStatus.setVisibility(View.VISIBLE);
                }
                if (allSelect) {
                    ivEmployeesStatus.setBackgroundResource(R.drawable.icon_fx_select);
                } else {
                    if (entity.isSelect()) {
                        ivEmployeesStatus.setBackgroundResource(R.drawable.icon_fx_select);
                    } else {
                        ivEmployeesStatus.setBackgroundResource(R.drawable.shape_circle_dddddd_10);
                    }
                }

            }
            rlStatus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Utils.changeNumber(entity.getEmpNum()) == 0) {
                        //灰色不可选中
                        MyToast.show("当前组织下暂无可选员工");
                    } else {
                        if (entity.isSelect()) {
                            entity.setSelect(false);
                            ivStatus.setBackgroundResource(R.drawable.shape_circle_dddddd_10);
                            allSelect = false;
                            ivAllStatus.setBackgroundResource(R.drawable.shape_circle_dddddd_10);
                        } else {
                            entity.setSelect(true);
                            ivStatus.setBackgroundResource(R.drawable.icon_fx_select);
                        }
                        setAllNum(false);
                    }
                }
            });
            rlEmployeesStatus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (entity.isSelect()) {
                        entity.setSelect(false);
                        ivEmployeesStatus.setBackgroundResource(R.drawable.shape_circle_dddddd_10);
                        allSelect = false;
                        ivAllStatus.setBackgroundResource(R.drawable.shape_circle_dddddd_10);
                        setAllNum(false);
                    } else {
                        if ("2".equals(source) && selectAllNum >= 3) {
                            MyToast.show("面试官最多选择3人");
                        } else {
                            if ("7".equals(source) || "9".equals(source)) {
                                //类型7是单选
                                if (singleIndex >= 0) {
                                    if (singleIndex != helper.getItemPosition()) {
                                        list.get(singleIndex).setSelect(false);
                                        adapter.notifyItemChanged(singleIndex);
                                    }
                                }
                                MyApp.contactEntityLogList.clear();
                            }
                            singleIndex = helper.getItemPosition();
                            entity.setSelect(true);
                            ivEmployeesStatus.setBackgroundResource(R.drawable.icon_fx_select);
                            setAllNum(false);
                            if ("7".equals(source) || "9".equals(source)) {
                                HashMap<String, String> map = new HashMap<>();
                                map.put("Single_select", "Single_select");
                                map.put("level", nameList.size() + "");
                                EventBus.getDefault().post(new MyEvent(map));
                            }
                        }
                    }
                }
            });
            ivEmployees.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Urls.antiShake.check()) {
                        return;
                    }
                    Intent intent = new Intent(ContactsLogChoiceActivity.this,
                            PersonalHomeActivity.class);
                    intent.putExtra("employeeCode", entity.getEmployeeCode());
                    startActivity(intent);

                }
            });
            helper.getItemView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Urls.antiShake.check()) {
                        return;
                    }
                    if ("0".equals(entity.getType())) {
                        //是组织
                        if (Utils.changeNumber(entity.getEmpNum()) == 0) {
                            MyToast.show("组织下暂无可选人员");
                            return;
                        }
                        if (entity.isSelect() || entity.isHalfSelect()) {
                            for (int j = 0; j < MyApp.contactEntityLogList.size(); j++) {
                                if (entity.getEmployeeCode().equals(MyApp.contactEntityLogList.get(j).getEmployeeCode())) {
                                    MyApp.contactEntityLogList.remove(j);
                                }
                            }
                        }
                        if (Utils.isNull(hierarchyOrgCode)) {
                            hierarchyOrgCode = entity.getEmployeeCode();
                        } else {
                            hierarchyOrgCode = hierarchyOrgCode + "_" + entity.getEmployeeCode();
                        }
                        Intent intent = new Intent(ContactsLogChoiceActivity.this,
                                ContactsLogChoiceActivity.class);
                        intent.putExtra("source", source);
                        intent.putExtra("orgCode", entity.getEmployeeCode());
                        intent.putExtra("companyNmae", companyNmae);
                        intent.putExtra("oldDepartmentEntity", entity);
                        if (entity.isSelect()) {
                            intent.putExtra("oldDepartmentStatus", true);
                        } else {
                            intent.putExtra("oldDepartmentStatus", false);
                        }
                        if ("2".equals(source)) {
                            intent.putExtra("examCode", examCode);
                            intent.putExtra("examName", examName);
                            intent.putExtra("qrCodeValid", qrCodeValid);
                        }
                        if ("3".equals(source) || "10".equals(source) || "11".equals(source)) {
                            intent.putExtra("oldContactNum", oldContactNum);
                        }
                        if ("3".equals(source) || "11".equals(source) || "2".equals(source) || "7".equals(source) || "9".equals(source) || "10".equals(source)) {
                            intent.putExtra("hrName", hrName);
                        }
                        intent.putExtra("oldCompanyNmae", entity.getEmployeeName());
                        intent.putExtra("hierarchyOrgCode", hierarchyOrgCode);
                        intent.putStringArrayListExtra("nameList", nameList);
                        startActivity(intent);
                    }
                }
            });
        }
    }

    private void setAllNum(boolean isZero) {
        pepleNum = 0;
        if (common_title_txt == null) {
            return;
        }
        KLog.i(allSelect + "===" + isZero);
        if (allSelect) {
            //当前页全部全选
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getType().equals("1")) {
                    pepleNum = pepleNum + 1;
                } else {
                    pepleNum = pepleNum + Utils.changeNumber(list.get(i).getEmpNum());
                }
                for (int j = 0; j < MyApp.contactEntityLogList.size(); j++) {
                    if (list.get(i).getEmployeeCode().equals(MyApp.contactEntityLogList.get(j).getEmployeeCode())) {
                        MyApp.contactEntityLogList.remove(j);
                        if (j < MyApp.contactEntityLogList.size()) {
                            j--;
                        }
                    } else if (MyApp.contactEntityLogList.get(j).getHierarchyOrgCode().contains(list.get(i).getEmployeeCode())) {
                        MyApp.contactEntityLogList.remove(j);
                        if (j < MyApp.contactEntityLogList.size()) {
                            j--;
                        }
                    }
                }
                if ("0".equals(list.get(i).getType()) && Utils.changeNumber(list.get(i).getEmpNum()) == 0) {
                    list.get(i).setSelect(false);
                } else {
                    list.get(i).setSelect(true);
                    MyApp.contactEntityLogList.add(list.get(i));
                }
                list.get(i).setHalfSelect(false);
            }
        } else {
            for (int i = 0; i < list.size(); i++) {
                if (isZero) {
                    //当前页全部取消选择
                    list.get(i).setSelect(false);
                    for (int j = 0; j < MyApp.contactEntityLogList.size(); j++) {
                        if (list.get(i).getEmployeeCode().equals(MyApp.contactEntityLogList.get(j).getEmployeeCode())) {
                            MyApp.contactEntityLogList.remove(j);
                            if (j < MyApp.contactEntityLogList.size()) {
                                j--;
                            }
                        }
                    }

                } else {
                    for (int j = 0; j < MyApp.contactEntityLogList.size(); j++) {
                        if (list.get(i).isSelect()) {
                            if (list.get(i).getEmployeeCode().equals(MyApp.contactEntityLogList.get(j).getEmployeeCode()) || MyApp.contactEntityLogList.get(j).getHierarchyOrgCode().contains(list.get(i).getEmployeeCode())) {
                                MyApp.contactEntityLogList.remove(j);
                                if (j < MyApp.contactEntityLogList.size()) {
                                    j--;
                                }
                            }
                        } else {
                            if (list.get(i).getEmployeeCode().equals(MyApp.contactEntityLogList.get(j).getEmployeeCode()) && !MyApp.contactEntityLogList.get(j).isHalfSelect()) {
                                MyApp.contactEntityLogList.remove(j);
                                if (j < MyApp.contactEntityLogList.size()) {
                                    j--;
                                }
                            }
                        }
                    }
                    if (list.get(i).isSelect()) {
                        list.get(i).setHalfSelect(false);
                        MyApp.contactEntityLogList.add(list.get(i));
                        if (list.get(i).getType().equals("1")) {
                            pepleNum = pepleNum + 1;
                        } else {
                            pepleNum = pepleNum + Utils.changeNumber(list.get(i).getEmpNum());
                        }
                    }
                }
            }
        }
        adapter.notifyDataSetChanged();
        changeSelectStatus();
    }

    private void changeSelectStatus() {
        if (common_title_txt == null) {
            return;
        }
        selectAllNum = 0;
        for (int i = 0; i < MyApp.contactEntityLogList.size(); i++) {
            if (!MyApp.contactEntityLogList.get(i).isHalfSelect()) {
                if (MyApp.contactEntityLogList.get(i).getType().equals("1")) {
                    selectAllNum = selectAllNum + 1;
                } else {
                    selectAllNum = selectAllNum + Utils.changeNumber(MyApp.contactEntityLogList.get(i).getEmpNum());
                }
            }
            KLog.i(MyApp.contactEntityLogList.get(i).getEmployeeName() + "==" + MyApp.contactEntityLogList.get(i).isSelect() + "==" + MyApp.contactEntityLogList.get(i).isHalfSelect() + MyApp.contactEntityLogList.get(i).getEmpNum());
        }
        if ("3".equals(source) || "11".equals(source)) {
            tvBottomNum.setText((selectAllNum - oldContactNum) + "人");
        } else {
            if (selectAllNum < 0) {
                tvBottomNum.setText("0人");
            } else {
                tvBottomNum.setText(selectAllNum + "人");
            }
        }
        if (selectAllNum > 0) {
            ivBottomSure.setText("选好了");
        } else {
            ivBottomSure.setText("不选了");
        }


        if (pepleNum == allNum) {
            if (!"2".equals(source)) {
                allSelect = true;
                ivAllStatus.setBackgroundResource(R.drawable.icon_fx_select);
            }
        } else {
            allSelect = false;
            ivAllStatus.setBackgroundResource(R.drawable.shape_circle_dddddd_10);
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        changeSelectStatus();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getHashMap() != null) {
            Map<String, String> map = messageEvent.getHashMap();
            if (map.containsKey("nextLayerSelectStatus") && map.containsKey(
                    "nextLayerSelectOrgCode")) {
                boolean nextLayerSelectStatus = Boolean.parseBoolean(map.get("nextLayerSelectStatus"));
                boolean halfSelect = Boolean.parseBoolean(map.get("halfSelect"));
                KLog.i("nextLayerSelectStatus=" + nextLayerSelectStatus + "--halfSelect=" + halfSelect);
                String nextLayerSelectOrgCode = map.get("nextLayerSelectOrgCode");
                pepleNum = 0;
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).getEmployeeCode().equals(nextLayerSelectOrgCode)) {
                        list.get(i).setSelect(nextLayerSelectStatus);
                        if (!nextLayerSelectStatus) {
                            if (halfSelect) {
                                list.get(i).setHalfSelect(true);
                            } else {
                                list.get(i).setHalfSelect(false);
                            }
                        } else {
                            list.get(i).setHalfSelect(false);
                        }
                        adapter.notifyItemChanged(i);
                    }
                    if (list.get(i).isSelect()) {
                        if (list.get(i).getType().equals("1")) {
                            pepleNum = pepleNum + 1;
                        } else {
                            pepleNum = pepleNum + Utils.changeNumber(list.get(i).getEmpNum());
                        }
                    }
                }
//                changeSelectStatus();
            }
            if (map.containsKey("Single_select")) {
                int oldLevel = Utils.changeNumber(map.get("level"));
                if (nameList.size() < oldLevel) {
                    //类型为7专用  单选清除之前页面的选择
                    for (int i = 0; i < list.size(); i++) {
                        list.get(i).setHalfSelect(false);
                        list.get(i).setSelect(false);
                    }
                    adapter.notifyDataSetChanged();
                    selectAllNum = MyApp.contactEntityLogList.size();
                    tvBottomNum.setText(selectAllNum + "人");
                    if (selectAllNum > 0) {
                        ivBottomSure.setText("选好了");
                    } else {
                        ivBottomSure.setText("不选了");
                    }
                }
            }
        } else {
            String msg = messageEvent.getMessage();
            if (Utils.isNull(msg)) {
                return;
            }
            if ("CloseContacts".equals(msg)) {
                //刷新最近列表
                finish();
            }
        }
    }

    @Override
    public void onBackPressed() {
        goBack();
    }

    private void goBack() {
        if ("2".equals(source)) {

        } else {
            HashMap<String, String> map = new HashMap<>();
            if (allSelect) {
                if (oldDepartmentEntity != null) {
                    for (int i = 0; i < list.size(); i++) {
                        for (int j = 0; j < MyApp.contactEntityLogList.size(); j++) {
                            if (list.get(i).getEmployeeCode().equals(MyApp.contactEntityLogList.get(j).getEmployeeCode())) {
                                MyApp.contactEntityLogList.remove(j);
                                if (j < MyApp.contactEntityLogList.size()) {
                                    j--;
                                }
                            } else if (MyApp.contactEntityLogList.get(j).getHierarchyOrgCode().contains(list.get(i).getEmployeeCode())) {
                                MyApp.contactEntityLogList.remove(j);
                                if (j < MyApp.contactEntityLogList.size()) {
                                    j--;
                                }
                            }
                        }
                        ;
                    }
                    oldDepartmentEntity.setHalfSelect(false);
                    oldDepartmentEntity.setSelect(true);
                }
                map.put("nextLayerSelectStatus", "true");
                map.put("halfSelect", "false");
            } else {
                if (oldDepartmentEntity != null) {
                    oldDepartmentEntity.setHalfSelect(false);
                    oldDepartmentEntity.setSelect(false);
                }
                map.put("nextLayerSelectStatus", "false");
                map.put("halfSelect", "false");
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).isHalfSelect()) {
                        //下一层级选中的人数，如果nextLayerSelectStatus为ture表示全选此字段无用  false的时候此字段判断是全部没有选中，还是选中一部分
                        map.put("halfSelect", "true");
                        if (oldDepartmentEntity != null) {
                            oldDepartmentEntity.setHalfSelect(true);
                        }
                    }
                }
                if (pepleNum > 0) {
                    map.put("halfSelect", "true");
                    if (oldDepartmentEntity != null) {
                        oldDepartmentEntity.setHalfSelect(true);
                    }
                }
            }
            if ("true".equals(map.get("nextLayerSelectStatus")) || "true".equals(map.get("halfSelect"))) {
                if (oldDepartmentEntity != null) {
                    MyApp.contactEntityLogList.add(oldDepartmentEntity);
                }
            }
            map.put("nextLayerSelectOrgCode", orgCode);
            EventBus.getDefault().post(new MyEvent(map));
        }
        finish();
    }

    @OnClick({R.id.common_title_back, R.id.ivBottomSure, R.id.rlStatus})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_title_back:
                goBack();
                break;
            case R.id.ivBottomSure:
                if ("2".equals(source)) {
                    Intent intent = new Intent(this, InterviewDetailActivity.class);
                    intent.putExtra("examCode", examCode);
                    intent.putExtra("examName", examName);
                    intent.putExtra("qrCodeValid", qrCodeValid);
                    startActivity(intent);
                    EventBus.getDefault().post(new MyEvent("CloseContacts"));
                } else if ("3".equals(source) || "10".equals(source) || "11".equals(source)) {
                    EventBus.getDefault().post(new MyEvent("ChoiceContacts_Ok_" + source));
                    EventBus.getDefault().post(new MyEvent("CloseContacts"));
                } else if ("7".equals(source) || "9".equals(source)) {
                    EventBus.getDefault().post(new MyEvent("ChoiceContacts_Ok_" + source));
                    EventBus.getDefault().post(new MyEvent("CloseContacts"));
                } else {
//                    if (MyApp.contactEntityLogList.size() > 0) {
                    if (allSelect) {
                        if (oldDepartmentEntity != null) {
                            for (int i = 0; i < list.size(); i++) {
                                for (int j = 0; j < MyApp.contactEntityLogList.size(); j++) {
                                    if (list.get(i).getEmployeeCode().equals(MyApp.contactEntityLogList.get(j).getEmployeeCode())) {
                                        MyApp.contactEntityLogList.remove(j);
                                        if (j < MyApp.contactEntityLogList.size()) {
                                            j--;
                                        }
                                    } else if (MyApp.contactEntityLogList.get(j).getHierarchyOrgCode().contains(list.get(i).getEmployeeCode())) {
                                        MyApp.contactEntityLogList.remove(j);
                                        if (j < MyApp.contactEntityLogList.size()) {
                                            j--;
                                        }
                                    }
                                }
                                ;
                            }
                            oldDepartmentEntity.setHalfSelect(false);
                            oldDepartmentEntity.setSelect(true);
                            MyApp.contactEntityLogList.add(oldDepartmentEntity);
                        }
                    } else {
                        if (pepleNum > 0) {
                            if (oldDepartmentEntity != null) {
                                oldDepartmentEntity.setHalfSelect(true);
                                oldDepartmentEntity.setSelect(false);
                                MyApp.contactEntityLogList.add(oldDepartmentEntity);
                            }
                        }
                    }
                    EventBus.getDefault().post(new MyEvent("ChoiceContacts_Ok_" + source));
//                    }
                    EventBus.getDefault().post(new MyEvent("CloseContacts"));
                }

                break;
            case R.id.rlStatus:
                if (ivAllStatus == null) {
                    return;
                }
                if (allSelect) {
                    allSelect = false;
                    ivAllStatus.setBackgroundResource(R.drawable.shape_circle_dddddd_10);
                    setAllNum(true);
                } else {
                    allSelect = true;
                    ivAllStatus.setBackgroundResource(R.drawable.icon_fx_select);
                    setAllNum(false);
                }
                adapter.notifyDataSetChanged();
                break;
        }
    }

    class FlowAdapter extends FlowLayout.Adapter<FlowAdapter.FlowViewHolder> {

        private static final String TAG = "FlowAdapter";

        private Context mContext;
        private List<String> mContentList;

        public FlowAdapter(Context mContext, List<String> mContentList) {
            this.mContext = mContext;
            this.mContentList = mContentList;
        }

        @Override
        public FlowViewHolder onCreateViewHolder(ViewGroup parent) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.item_contacts_name_list,
                    parent, false);

            return new FlowViewHolder(view);
        }

        @Override
        public void onBindViewHolder(FlowViewHolder holder, int position) {
            holder.tvTitle.setText(mContentList.get(position));
            if (position == 0) {
                holder.ivArrow.setVisibility(View.GONE);
                holder.tvTitle.setTextColor(Color.parseColor("#818080"));
            } else {
                holder.ivArrow.setVisibility(View.VISIBLE);
                holder.tvTitle.setTextColor(Color.parseColor("#333333"));
            }
        }

        @Override
        public int getItemCount() {
            return mContentList.size();
        }

        class FlowViewHolder extends FlowLayout.ViewHolder {
            TextView tvTitle;
            ImageView ivArrow;

            public FlowViewHolder(View itemView) {
                super(itemView);
                tvTitle = itemView.findViewById(R.id.tvTitle);
                ivArrow = itemView.findViewById(R.id.ivArrow);
            }
        }
    }

    private void loadEnd() {
        if (null != srlView && srlView.getState() == RefreshState.Refreshing)
            srlView.finishRefresh(true);
        if (null != srlView && srlView.getState() == RefreshState.Loading)
            srlView.finishLoadMore(true);
    }
}
